package cn.com.fone.modules.admin.common.config;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Map;

/**
 * 集群方式redis客户端操作
 *
 * @author dream21th
 */
@Service("jedisClusterClient")
public class JedisClusterClient {
    @Autowired
    private JedisCluster jedisCluster;
    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;
    @Autowired
    private RedisTemplate redisTemplate;



    private static final Logger log = LoggerFactory.getLogger(JedisClusterClient.class);

    /**
     * 获取指定前缀所有key
     *
     * @return
     */
    public List<String> keys(String prefix) {
        log.info("=>模糊查询key:{}", prefix);
        List<String> keys = Lists.newArrayList();
        // 获取所有连接池节点
        Map<String, JedisPool> nodes = jedisCluster.getClusterNodes();
        // 遍历所有连接池，逐个进行模糊查询
        nodes.keySet().forEach(v -> {
            log.debug(" == 从节点：{}获取key", v);
            JedisPool pool = nodes.get(v);
            // 获取Jedis对象，Jedis对象支持keys模糊查询
            try (Jedis connection = pool.getResource()) {
                keys.addAll(connection.keys(prefix));
            } catch (Exception e) {
                log.error("<=  获取key异常", e);
            }
        });
        log.info("<= 获取可以完成,总共：{}", keys.size());
        return keys;
    }

    /**
     * 获取redis单个key
     *
     * @param key
     * @return
     */
    public JSONObject getKey(String key) {

        JSONObject respJson = new JSONObject();
        respJson.put("value", redisTemplate.opsForValue().get(""));
        return null;
    }
}